package com.sc.nft.admin.service.impl;

import cn.hutool.core.date.SystemClock;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.sc.nft.admin.config.QywxConfig;
import com.sc.nft.admin.service.QywxService;
import com.sc.nft.admin.util.qywx.AesException;
import com.sc.nft.admin.util.qywx.WXBizJsonMsgCrypt;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.SecondOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class QywxServiceImpl implements QywxService {

    private  final WXBizJsonMsgCrypt crypt;
    private  final QywxConfig qywxConfig;
    private  final SecondOrderService secondOrderService;
    private final RedisTemplate redisTemplate;

    @Override
    public String handleMsg(String msg, String timestamp, String nonce, String postData) throws AesException {
        String resultStr = crypt.VerifyURL(msg, timestamp, nonce, postData);
        log.info("result {}", resultStr);
        Map<String, Object> result = XmlUtil.xmlToMap(resultStr);
        String MsgType = MapUtil.getStr(result,"MsgType");
        if(StrUtil.equals(MsgType,"text")){{
            String content = MapUtil.getStr(result,"Content", StrUtil.EMPTY);
            String answer;
            if(StrUtil.startWith(content,"解") && content.length() == 12){
                try{
                    secondOrderService.unfreeze(content.substring(1));
                    answer = "解冻成功";
                } catch (GlobalRunTimeException e) {
                    answer = e.getMessage();
                }
            }
            else{
                answer = "我暂时还不会处理这个问题，你可以联系管理员";
            }
            //回复消息
            return buildXml(MapUtil.getStr(result,"FromUserName"),MapUtil.getStr(result,"ToUserName"),answer,timestamp,nonce);
        }}
        return buildXml(MapUtil.getStr(result,"FromUserName"),MapUtil.getStr(result,"ToUserName"),"我不懂你再说什么",timestamp,nonce);

    }


    //构建企业微信回复消息xml
    private String buildXml(String toUserName,String fromUserName,String content,String timestamp,String nonce) throws AesException {
        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.put("ToUserName", toUserName);
        resultMap.put("FromUserName", fromUserName);
        resultMap.put("CreateTime", SystemClock.now() / 1000);
        resultMap.put("MsgType", "text");
        resultMap.put("Content", content);
        return  crypt.EncryptMsg(XmlUtil.mapToXmlStr(resultMap), timestamp, nonce);
     }

     @Override
    public void sendWeChatMessage(String message, String toUser) {

        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+qywxConfig.getWeChatToken();
        JSONObject pram = new JSONObject();

        pram.put("touser", toUser);
        pram.put("msgtype", "text");
        pram.put("agentid", qywxConfig.agentid);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", message);
        pram.put("text", jsonObject);
        String post = HttpUtil.post(url, pram.toJSONString());
        log.info("post:{}",post);
    }
}
